package com.lkd.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.lkd.common.VMSystem;
import com.lkd.entity.VendingMachineEntity;
import com.lkd.service.VendingMachineService;
import com.lkd.utils.JsonUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.util.ShardingUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.*;

/**
 * @Author : Bing
 * @Date 2023/3/4 16:43
 */
@Component
@Slf4j
public class SupplyJob {

    @Autowired
    private VendingMachineService vendingMachineService;

//    ExecutorService executorService = Executors.newFixedThreadPool(10);

    ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
            .setNameFormat("demo-pool-%d").build();

    //Common Thread Pool
    ExecutorService executorService = new ThreadPoolExecutor(10, 10,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());

    @XxlJob("supplyJobHandler")
    public ReturnT<String> workCountInitJobHandler(String param) {

        ShardingUtil.ShardingVO shardingVo = ShardingUtil.getShardingVo();
        //分片总数
        int total = shardingVo.getTotal();
        //当前分片索引
        int index = shardingVo.getIndex();

        //获取运营状态下的所有售货机信息
        LambdaQueryWrapper<VendingMachineEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VendingMachineEntity::getVmStatus, VMSystem.VM_STATUS_RUNNING)
                .apply("mod(id," + total + ")=" + index);
        List<VendingMachineEntity> vmes = vendingMachineService.list(wrapper);

        vmes.forEach(each -> {

            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    vendingMachineService.getAllSupplyList(each);
                }
            });

            try {
                log.info("分片总数：{}，当前索引：{}，售货机信息:{}",total, index, JsonUtil.serialize(vmes));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        });


        return ReturnT.SUCCESS;
    }


}
